package mt.dummy;

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

import mt.Order;
import mt.client.MicroTraderClient;
import mt.comm.ClientComm;
import mt.comm.ClientSideMessage;

/**
 * Creates the interface for the client.
 */

public class MicroTraderClientDummy extends JFrame implements MicroTraderClient {
        private static final long serialVersionUID = 1L;
        /**
         * The constructor of the class
         */
        public ClientComm clientComm;
        List<Order> orders = new LinkedList<Order>();
        public JTable orderList;
        public String[] ordersArray;

        String[] columnNames = { "Stock", "Number of units", "Price per unit",
                        "Buy/Sell" };

        /**
         * Displays the layout of the client window A table with the stock, number
         * of units and price per unit Buttons for connecting and disconnecting to
         * the server and a button for placing a order Info about the server
         * 
         * @param clientComm
         */
        @Override
        public void start(final ClientComm clientComm) {
                setLayout(new FlowLayout());
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                String[] uselessRow = { "(Name of the stock)",
                                "(Number of units for sale )", "(Price of each stock unit)",
                                "(Type of Stock" };
                ClientTable model = new ClientTable(uselessRow, columnNames);

                orderList = new JTable(model) {
                        private static final long serialVersionUID = 1L;

                        // Renders the JTable when a change has been applied
                        public Component prepareRenderer(TableCellRenderer tcr, int data,
                                        int columns) {
                                Component c = super.prepareRenderer(tcr, data, columns);
                                if (data == 0) {
                                        c.setBackground(Color.gray);
                                }
                                return c;
                        }
                };

                JTableHeader tableHeader = orderList.getTableHeader();
                tableHeader.setFont(new Font("Dialog", Font.CENTER_BASELINE, 12));
                tableHeader.setBackground(Color.blue);
                tableHeader.setForeground(Color.white);

                orderList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                add(new JScrollPane(orderList), FlowLayout.LEFT);

                this.setSize(800, 600);
                this.clientComm = clientComm;

                JButton bPlaceOrder = new JButton("Place Order");
                JButton bConnect = new JButton("Connect");
                JButton bDisconnect = new JButton("Disconnect");

                final JTextField tfServerAdress = new JTextField("localhost");
                final JTextField tfNickname = new JTextField("NickName");
                final JTextField tfStock = new JTextField("Stock name");
                final JTextField tfBuyOrSell = new JTextField("B");
                final JTextField tfPricePerUnit = new JTextField("1",2);
                final JTextField tfNumberOfUnits = new JTextField("6",2);

                bConnect.addActionListener(new ActionListener() {

                        /**
                         * Tries to make a connection with the server
                         */
                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                                try {
                                        clientComm.connect(tfServerAdress.getText(),
                                                        tfNickname.getText());
                                } catch (UnknownHostException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                });

                bDisconnect.addActionListener(new ActionListener() {

                        /**
                         * Disconnects with the server
                         */
                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                                clientComm.disconnect();
                        }
                });

                bPlaceOrder.addActionListener(new ActionListener() {

                        /**
                         * Places an Order
                         */
                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                                if (tfBuyOrSell.getText().equals("B")) {
                                        clientComm.sendOrder(Order.createBuyOrder(
                                                        tfNickname.getText(), tfStock.getText(),
                                                        Integer.parseInt(tfNumberOfUnits.getText()),
                                                        Double.parseDouble(tfPricePerUnit.getText())));
                                }
                                if (tfBuyOrSell.getText().equals("S")) {
                                        clientComm.sendOrder(Order.createSellOrder(
                                                        tfNickname.getText(), tfStock.getText(),
                                                        Integer.parseInt(tfNumberOfUnits.getText()),
                                                        Double.parseDouble(tfPricePerUnit.getText())));
                                }
                        }
                });
                add(bPlaceOrder);
                add(bConnect);
                add(bDisconnect);
                add(tfServerAdress);
                add(tfNickname);
                add(tfStock);
                add(tfBuyOrSell);
                add(tfPricePerUnit);
                add(tfNumberOfUnits);
                this.setVisible(true);

                while (true) {
                        try {
                                Thread.sleep(500);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        while (clientComm.isConnected()) {
                                if (clientComm.hasNextMessage()) {
                                        ClientSideMessage msg = clientComm.getNextMessage();
                                        System.out.println("ORDEM BARAYTA =====================> "
                                                        + msg.getOrder().toString());
                                        switch (msg.getType()) {
                                        case ERROR:
                                                JOptionPane.showMessageDialog(null, msg.getError(),
                                                                "Error Message",
                                                                JOptionPane.INFORMATION_MESSAGE);
                                                this.repaint();
                                                break;
                                        case ORDER:
                                                System.out.println("RM: " + msg.getOrder().getNumberOfUnits());
                                                model.add(msg.getOrder().getStock(), String.valueOf(msg
                                                                .getOrder().getNumberOfUnits()), String
                                                                .valueOf(msg.getOrder().getPricePerUnit()), msg
                                                                .getOrder().isBuyOrder(), msg.getOrder().getServerOrderID());
                                                System.out.println("BUY ORDER? ==> "
                                                                + msg.getOrder().isBuyOrder());
                                                break;
                                        }
                                }
                        }
                }
        }
}